﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace WebApplication2.Controllers
{
    public class UploadController : ApiController
    {
        private string uploadPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Upload/";

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns>成功返回图片URL，失败则返回错误信息</returns>
        public string Post()
        {
            string result = string.Empty;
            string imgPath = string.Empty;

            HttpRequest request = System.Web.HttpContext.Current.Request;
            HttpFileCollection fileCollection = request.Files;

            // 判断是否有文件
            if (fileCollection.Count > 0)
            {
                // 获取图片文件
                HttpPostedFile httpPostedFile = fileCollection[0];
                // 文件扩展名
                string fileExtension = Path.GetExtension(httpPostedFile.FileName);
                // 图片名称
                string fileName = Guid.NewGuid().ToString() + fileExtension;
                // 图片上传路径
                string filePath = uploadPath + fileName;

                // 验证图片格式
                if (fileExtension.Contains(".jpg")
                    || fileExtension.Contains(".png")
                    || fileExtension.Contains(".bmp"))
                {
                    // 如果目录不存在则要先创建
                    if (!Directory.Exists(uploadPath))
                    {
                        Directory.CreateDirectory(uploadPath);
                    }

                    // 保存新的图片文件
                    while (File.Exists(filePath))
                    {
                        fileName = Guid.NewGuid().ToString() + fileExtension;
                        filePath = uploadPath + fileName;
                    }
                    httpPostedFile.SaveAs(filePath);

                    // 把文件的存储路径保存起来
                    //SaveUploadFileInfo(fileName, filePath);

                    // 返回图片URL
                    imgPath = request.Url.Scheme + "://"+ request.Url.Authority + "/Upload/"  + fileName;
                    result = imgPath;
                }
                else
                {
                    result = "请选择jpg/png/bmp格式的图片";
                }
            }
            else
            {
                result = "请先选择图片！";
            }

            return result;
        }
    }
}
